# -*- coding: utf-8 -*-

import re
from urllib.parse import urljoin

from odoo.http import request
from odoo_contrib.marshmallow import fields
from odoo_contrib.utils.common import convert_to_video_url
from ...utils.settings import Settings


RE_HTML_FONT_LABEL = re.compile(r'([</])font')
RE_HTML_SECTION_LABEL = re.compile(r'([</])section')

VIDEO_URL_PREFIX = '/assets/video'


class VideoUrl(fields.Str):
    def __init__(self, *args, model_xmlid=None, filename_field=None, **kwargs):
        super().__init__(*args, **kwargs)
        assert model_xmlid, 'Must specify model_xmlid for VideoUrl field'
        assert filename_field, 'Must specify filename_field for VideoUrl field'
        self.model_xmlid = model_xmlid
        self.filename_field = filename_field

    def _serialize(self, value, attr, obj, **kwargs):
        if not Settings().video_on:
            value = False
        if value:
            value = convert_to_video_url(obj.ids[0], self.model_xmlid, self.attribute or attr, self.filename_field, url_prefix='/web/content/')
        else:
            value = False
        return super()._serialize(value, attr, obj, **kwargs)

    def _get_video(self, obj):
        obj = obj[0]


class VideoUrlPath(fields.Str):
    def __init__(self, *args, model_xmlid=None, filename_field=None, **kwargs):
        super().__init__(*args, **kwargs)
        assert model_xmlid, 'Must specify model_xmlid for VideoUrl field'
        self.model_xmlid = model_xmlid
        self.filename_field = filename_field

    def _serialize(self, value, attr, obj, **kwargs):
        if not Settings().video_on:
            value = False
        if value:
            value = self._get_video(obj, attr)
        else:
            value = False
        return super()._serialize(value, attr, obj, **kwargs)

    def _get_video(self, obj, attr):
        domains = [
            ('res_model', '=', self.model_xmlid),
            ('res_field', '=', self.attribute or attr),
            ('res_id', 'in', obj.ids),
        ]
        attachment = request.env['ir.attachment'].sudo().search(domains, limit=1)
        if attachment:
            fname = attachment.store_fname
            try:
                host_url = request.httprequest.host_url
                fname = fname.lstrip('/')
                url_prefix = Settings().video_url_prefix.rstrip('/') + '/'
                url_prefix = urljoin(host_url, url_prefix)
                return urljoin(url_prefix, fname)
            except:
                return False
        else:
            return False


class Html(fields.Html):
    def _serialize(self, value, attr, obj, **kwargs):
        if value:
            value = RE_HTML_FONT_LABEL.sub(r'\1span', value)
        if value:
            value = RE_HTML_SECTION_LABEL.sub(r'\1div', value)
        return super()._serialize(value, attr, obj, **kwargs)
